package com.acme.bankapp.service.bank;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class BankClient {
	public static void startClient() {
		Socket requestSocket = null;
		ObjectOutputStream out = null;
		ObjectInputStream in = null;
		String message = null;

		try {
			requestSocket = new Socket("localhost", BankServer.SERVER_PORT);
			out = new ObjectOutputStream(requestSocket.getOutputStream());
			out.flush();
			in = new ObjectInputStream(requestSocket.getInputStream());

			try {
				message = (String) in.readObject();
				if (BankServer.MESSAGE_BEGIN.equals(message)) {
					sendMessage(out, BankServer.MESSAGE_ADD_ACCOUNT);
					sendMessage(out, "accounttype=c;balance=54;overdraft=45;name=Nur;gender=f;");
					message = (String) in.readObject();
					printMessage(message);



					sendMessage(out, BankServer.MESSAGE_PRINT_BALANCE);
					message = (String) in.readObject();
					printMessage(message);

					sendMessage(out, BankServer.MESSAGE_PRINT_MAXIMUM);
					message = (String) in.readObject();
					printMessage(message);

					sendMessage(out, BankServer.MESSAGE_END);
				}
			} catch (ClassNotFoundException exception) {
				System.out.println("Error with serilization");
			}
		} catch (UnknownHostException exception) {
			System.out.println("Error connect to wrong host");
		} catch (IOException exception) {
			System.out.println("Error IO with stream");
		} finally {
			try {
				if (in != null)
					in.close();
				if (out != null)
					out.close();
				if (requestSocket != null)
					requestSocket.close();
			} catch (IOException exception) {
				System.out.println("Error close client");
			}
		}
	}

	private static void printMessage(String message) {
		System.out.println(message);
	}

	private static void sendMessage(ObjectOutputStream out, final String message) {
		try {
			out.writeObject(message);
			out.flush();
		} catch (IOException exception) {
			System.out.println("Error when server try send message to client. Msg: " + message);
		}
	}
}
